package com.china08.yxyapi.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.model.YxyApiRespModel;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 云校云平台-对象存储云:工具类
 * 
 * @author Ertao.Fang
 * 
 */
@Component
public class YxyOscUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyOscUtil.class);

    @Value("${spring.profiles.active}")
    private String profile;

    @Value("${ceph.aws.s3.endpoint.push.url}")
    private String pushPath = "https://localhost:8080/yxyosc/push/";

    private SimpleDateFormat tmpDirSimpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上传文件
     * 
     * @param file
     * @throws IOException
     */
    public String push(MultipartFile multipartFile) throws IOException {

        long pushTimeB = System.currentTimeMillis();
        LOGGER.info(StringUtils.repeat("**", 25));
        LOGGER.info("上传开始...");

        // ##
        // 1. 创建临时文件
        File tmpFile = createTmpFile(multipartFile);

        // ##
        // 2. 创建FileSystemResource, 提供RestTemplate使用
        FileSystemResource resource = new FileSystemResource(tmpFile);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        param.add("filename", resource.getFilename());// MultipartFile获取到的中文名有乱码
        param.add("profile", profile);
        param.add("pushPath", pushPath);

        // ##
        // 3.上传文件: 使用RestTemplate
        RespModel respModel = restTemplate.postForObject(pushPath, param, RespModel.class);
        System.out.println(new ObjectMapper().writeValueAsString(respModel));

        String fileUrl = respModel.fileUrl;
        long pushTimeE = System.currentTimeMillis();
        LOGGER.info("上传结束:用时:[" + (pushTimeE - pushTimeB) + "ms]");
        LOGGER.info(StringUtils.repeat("**", 25));

        return fileUrl;
    }

    /**
     * 创建临时文件
     * 
     * @param multipartFile
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public File createTmpFile(MultipartFile multipartFile) throws IllegalStateException, IOException {
        String fileName = multipartFile.getOriginalFilename();
        String tmpDirPath = FileUtils.getTempDirectoryPath() + "/yxyosc/" + tmpDirSimpleDateFormat.format(new Date());
        File tmpDir = new File(tmpDirPath);
        tmpDir.mkdirs();
        String tmpFilePath = tmpDirPath + "/" + fileName;
        File tmpFile = new File(tmpFilePath);
        multipartFile.transferTo(tmpFile);
        return tmpFile;
    }

    protected static class RespModel extends YxyApiRespModel {
        public String fileUrl;
        public long duration = 0;
    }

    // public static void main(String[] args) {
    // YxyOscUtil yxyOscUtil = new YxyOscUtil();
    // try {
    // File file = new File("c:\\七年级上册《声母韵母》教案.doc");
    // String originalFilename = file.getName();
    // byte[] content = FileUtils.readFileToByteArray(file);
    // MockMultipartFile multipartFile = new MockMultipartFile("file",
    // originalFilename,
    // MediaType.APPLICATION_OCTET_STREAM_VALUE, content);
    // String fileUrl = yxyOscUtil.push(multipartFile);
    // System.out.println(fileUrl);
    // } catch (HttpServerErrorException e) {
    // e.printStackTrace();
    // e.getResponseBodyAsString();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
}
